﻿using System;
using System.Collections.Generic;
using System.Linq;
using Volo.Abp.Validation.StringValues;

namespace Xms.Abp.Validation.StringValues;

[Serializable]
[StringValueType("ARRAY")]
public class ArrayValueValidator : ValueValidatorBase
{
    public override bool IsValid(object value)
    {
        if (value is Array)
        {
            return IsValidElementType(value.GetType().GetElementType());
        }

        if (value is System.Collections.IEnumerable)
        {
            return IsValidElementType(value.GetType().GetInterfaces().First(r => r.Name == typeof(IEnumerable<>).Name).GetGenericArguments().First());
        }

        if (value is System.Collections.ICollection)
        {
            return IsValidElementType(value.GetType().GetInterfaces().First(r => r.Name == typeof(ICollection<>).Name).GetGenericArguments().First());
        }

        return false;
    }

    protected bool IsValidElementType(Type type)
    {
        return type == typeof(string) || type.IsValueType;
    }
}
